<!-- views/Login.vue  -->
<template>
  <div class="login-container tree-bg">
    <div class="login-box">
      <div class="tree-logo">
        <img src="@/assets/image/tree-logo.jpg" alt="树木Logo">
        <h2>古树木管理系统</h2>
      </div>

      <el-tabs v-model="activeTab" class="login-tabs">
        <el-tab-pane label="密码登录" name="password">
          <el-form :model="pwdForm" :rules="rules" ref="pwdFormRef">
            <el-form-item prop="phone">
              <el-input v-model="pwdForm.phone" placeholder="请输入手机号" prefix-icon="el-icon-mobile-phone">
              </el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input v-model="pwdForm.password" type="password" placeholder="请输入密码" prefix-icon="el-icon-lock"
                show-password>
              </el-input>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <el-tab-pane label="验证码登录" name="sms">
          <el-form :model="smsForm" :rules="rules" ref="smsFormRef">
            <el-form-item prop="phone">
              <el-input v-model="smsForm.phone" placeholder="请输入手机号" prefix-icon="el-icon-mobile-phone">
              </el-input>
            </el-form-item>
            <el-form-item prop="code">
              <div class="code-input">
                <el-input v-model="smsForm.captcha" placeholder="请输入验证码" prefix-icon="el-icon-message">
                </el-input>
                <el-button :disabled="isCounting" @click="getSmsCode" class="code-btn">
                  {{ codeBtnText }}
                </el-button>
              </div>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>

      <el-button type="primary" class="login-btn" @click="handleLogin" :loading="loading">
        登录
      </el-button>

      <div class="login-footer">
        <span @click="gotoRegister">还没有账号？立即注册</span>
        <span class="leaf-divider">
          <img src="@/assets/image/leaf.jpg" alt="树叶装饰">
        </span>
        <span @click="forgetPassword">忘记密码</span>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { nextTick } from 'vue'
import { mapMenusToRoutes } from '@/utils/map-menu'
import { userLoginStore } from '@/store/login/login'
import { sendCaptcha, getMenu } from '@/api/user'
import localCache from '@/utils/cache'
/* import { mapMenusRoutes } from '@/utils/map-menus'

import { useTokenStore } from '@/store/userStore'
import { usemenuStore } from '@/store/menuStore'
import { getMenuRequest } from '@/api/auth'
import { map } from 'lodash'
import { nextTick } from 'vue'
 */

const router = useRouter()

// 响应式状态
const activeTab = ref<'password' | 'sms'>('password')
const loading = ref(false)
const isCounting = ref(false)
const codeBtnText = ref('获取验证码')
const pwdFormRef = ref<FormInstance>()
const smsFormRef = ref<FormInstance>()
let countdown = 60

// 表单数据
const pwdForm = reactive({
  phone: '',
  password: '',
})

const smsForm = reactive({
  phone: '',
  captcha: ''
})

// 验证规则
const rules: FormRules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在6到20个字符', trigger: 'blur' }
  ],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { pattern: /^\d{6}$/, message: '验证码为6位数字', trigger: 'blur' }
  ]
}

// 获取验证码
const getSmsCode = async () => {
  try {
    await smsFormRef.value?.validateField('phone')
    isCounting.value = true

    const result = await sendCaptcha(smsForm.phone)
    if (result.code === 1) {
      ElMessage.success(' 验证码已发送')
      startCountdown()
    } else {
      ElMessage.error(result.msg || '验证码发送失败')
      resetCodeButton()
      smsForm.captcha = ''
    }
  } catch (error) {
    console.error(' 验证码请求失败:', error)
    resetCodeButton()
    ElMessage.error(' 验证码发送异常')
  }
}

// 倒计时逻辑
const startCountdown = () => {
  const timer = setInterval(() => {
    countdown--
    codeBtnText.value = `${countdown}s后重新获取`
    if (countdown <= 0) {
      clearInterval(timer)
      resetCodeButton()
    }
  }, 1000)
}

// 重置验证码按钮状态
const resetCodeButton = () => {
  isCounting.value = false
  codeBtnText.value = '获取验证码'
  countdown = 60
}

// 登录处理
const handleLogin = async () => {
  const formRef = activeTab.value === 'password' ? pwdFormRef.value : smsFormRef.value
  if (!formRef) return

  try {
    await formRef.validate()
    loading.value = true

    // 根据登录方式构造不同参数
    const loginParams = activeTab.value === 'password'
      ? { phone: pwdForm.phone, password: pwdForm.password } : { phone: smsForm.phone, captcha: smsForm.captcha }

    const loginStore = userLoginStore()
    const result = await loginStore.setUserInfo(loginParams, activeTab.value === 'password')
    // 调用统一登录接口
    /* = await userLogin(
       loginParams,
       activeTab.value === 'password' // 第二个参数表示是否密码登录
     ) */
    if (result.code === 1) {
      ElMessage.success(' 登录成功')
      //保存后端返回的信息

      await nextTick()

      const menuResult = await getMenu()
      loginStore.menu = menuResult.data
      localCache.setCache('menu', menuResult.data)

      const routes = mapMenusToRoutes(menuResult.data)
      routes.forEach((route) => {
        router.addRoute('main', route)
      })


      // 跳转到仪表板页面
      router.push('/main')
    } else {
      ElMessage.error(result.msg || '登录失败')
      if (activeTab.value === 'password') {
        pwdForm.password = ''
      }
    }
  } catch (error) {
    console.error(' 登录异常:', error)
    ElMessage.error(' 登录过程中发生错误')
  } finally {
    loading.value = false
  }
}

// 辅助功能
const gotoRegister = () => router.push('/register')
const forgetPassword = () => ElMessage.warning(' 请联系管理员重置密码')
</script>

<style lang="scss" scoped>
.login-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f7fa;

  &.tree-bg {
    background-image: url('@/assets/image/tree-bg-light.jpg');
    background-size: cover;
    background-position: center;
  }
}

.login-box {
  width: 400px;
  padding: 40px;
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 10px;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
  border: 1px solid #e8e8e8;
}

.tree-logo {
  text-align: center;
  margin-bottom: 30px;

  img {
    width: 80px;
    height: 80px;
  }

  h2 {
    margin-top: 10px;
    color: #3a7d34;
    font-weight: 500;
  }
}

.login-tabs {
  :deep(.el-tabs__item) {
    font-size: 16px;
    color: #666;

    &.is-active {
      color: #3a7d34;
    }
  }

  :deep(.el-tabs__active-bar) {
    background-color: #3a7d34;
  }
}

.code-input {
  display: flex;

  .el-input {
    flex: 1;
  }

  .code-btn {
    margin-left: 10px;
    width: 120px;
  }
}

.login-btn {
  width: 100%;
  margin-top: 20px;
  background-color: #3a7d34;
  border-color: #3a7d34;
  font-size: 16px;
  height: 45px;

  &:hover {
    background-color: #4d9c46;
    border-color: #4d9c46;
  }
}

.login-footer {
  margin-top: 20px;
  text-align: center;
  color: #999;
  font-size: 14px;

  span {
    cursor: pointer;
    transition: color 0.3s;

    &:hover {
      color: #3a7d34;
    }
  }

  .leaf-divider {
    display: inline-block;
    margin: 0 15px;

    img {
      width: 16px;
      height: 16px;
      vertical-align: middle;
    }
  }
}
</style>
